/*
 * SHOPTNT 版权所有。
 * 未经许可，您不得使用此文件。
 * 官方地址：www.shoptnt.cn
 */
package cn.shoptnt.framework.util;


import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.IOUtils;

import javax.crypto.Cipher;
import java.io.ByteArrayOutputStream;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;

/**
 * @author fk
 * @version v7.0
 * @Description RSA加解密工具
 * @since v7.2.3
 * 2021年11月11日14:37:58
 */
public class RSAUtil {

    public static final String CHARSET = "UTF-8";
    public static final String RSA_ALGORITHM = "RSA";
    public static final String PRIVATE_KEY = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAIofO4ITPywLX7MHgqopbdtoECbyJgXQdDaxbO4hgWE7Jt0G8UoMSi6H_CFPW2dH1vsxnhG5-C3kdLga6xuvdBeotfCoIihDqdcoMu0D1PJx2kPrCNic0OZ979BE_j9NOZGyIHQDaJuAA8Y1Kz9LuD63S1L5rripOUxznZt2So1rAgMBAAECgYBHPCRsyZBjHtqUcuMo74UBC4KJE4oYpZHKQ2dyyUT46JD6nYIENqJrrSaT52G0upBdrRFhAxDEWnb4HKn09WBhqplqU8ZrStqgHy2mUbM6BM_DTxod0Hv-Q0jyHu2iAawe4Z24qLH6W4px6P1M6QyGQ8buRu1ZnqlqPKBSFXX6gQJBAPTMvLrDukt_ucpG8Rw09CQnqPhViuRoHZXILrOMo9-UZ1vKeVG3eWXsF_kgy-C2VG6riQGZKXm9pxPS-ayJqDMCQQCQcQMckGy_d2g-nN7D3TkyyA3HJ4q3bRimqUGnBCviW-fioaQe27TAru_UUFQ5y8_dCNbkLsLmgfDTYZNiUq3pAkEAiF41FGVMNhqkyMXUMr5c8ncVbaFZiftl37ZwLZ0-_KGTIlMcWiU2_0wR3roiWL-5MR1laPqFXEgF9skkRLU6eQJAL-8hPjh7rmq9EJJUpyFiWwTi9aWctlShKqXe4MNUoPEpGh_UbF0zNgKYGphx6yBFIjBNyDnwejjDKBMoqyePCQJBAOJb-XcnUI6PZTybKOYx3dhXaMECGnVuEN6_ouys2pvKJXfwwpM4K5pBIPLc4BcjJPG0Qs3bYZ9R3DboMdfefFc";
    public static final String PUBLIC_KEY = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCKHzuCEz8sC1-zB4KqKW3baBAm8iYF0HQ2sWzuIYFhOybdBvFKDEouh_whT1tnR9b7MZ4Rufgt5HS4Gusbr3QXqLXwqCIoQ6nXKDLtA9TycdpD6wjYnNDmfe_QRP4_TTmRsiB0A2ibgAPGNSs_S7g-t0tS-a64qTlMc52bdkqNawIDAQAB";


    public static Map<String, String> createKeys(int keySize) {
        //为RSA算法创建一个KeyPairGenerator对象
        KeyPairGenerator kpg;
        try {
            kpg = KeyPairGenerator.getInstance(RSA_ALGORITHM);
        } catch (NoSuchAlgorithmException e) {
            throw new IllegalArgumentException("No such algorithm-->[" + RSA_ALGORITHM + "]");
        }

        //初始化KeyPairGenerator对象,密钥长度
        kpg.initialize(keySize);
        //生成密匙对
        KeyPair keyPair = kpg.generateKeyPair();
        //得到公钥
        Key publicKey = keyPair.getPublic();
        String publicKeyStr = Base64.encodeBase64URLSafeString(publicKey.getEncoded());
        //得到私钥
        Key privateKey = keyPair.getPrivate();
        String privateKeyStr = Base64.encodeBase64URLSafeString(privateKey.getEncoded());
        Map<String, String> keyPairMap = new HashMap<String, String>();
        keyPairMap.put("publicKey", publicKeyStr);
        keyPairMap.put("privateKey", privateKeyStr);

        return keyPairMap;
    }

    /**
     * 得到公钥
     *
     * @param publicKey 密钥字符串（经过base64编码）
     * @throws Exception
     */
    public static RSAPublicKey getPublicKey(String publicKey) throws NoSuchAlgorithmException, InvalidKeySpecException {
        //通过X509编码的Key指令获得公钥对象
        KeyFactory keyFactory = KeyFactory.getInstance(RSA_ALGORITHM);
        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(Base64.decodeBase64(publicKey));
        RSAPublicKey key = (RSAPublicKey) keyFactory.generatePublic(x509KeySpec);
        return key;
    }

    /**
     * 得到私钥
     *
     * @param privateKey 密钥字符串（经过base64编码）
     * @throws Exception
     */
    private static RSAPrivateKey getPrivateKey(String privateKey) throws NoSuchAlgorithmException, InvalidKeySpecException {
        //通过PKCS#8编码的Key指令获得私钥对象
        KeyFactory keyFactory = KeyFactory.getInstance(RSA_ALGORITHM);
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(Base64.decodeBase64(privateKey));
        RSAPrivateKey key = (RSAPrivateKey) keyFactory.generatePrivate(pkcs8KeySpec);
        return key;
    }

    /**
     * 公钥加密
     *
     * @param data
     * @param publicKey
     * @return
     */
    public static String publicEncrypt(String data, RSAPublicKey publicKey) {
        try {
            Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);
            return Base64.encodeBase64URLSafeString(rsaSplitCodec(cipher, Cipher.ENCRYPT_MODE, data.getBytes(CHARSET), publicKey.getModulus().bitLength()));
        } catch (Exception e) {
            throw new RuntimeException("加密字符串[" + data + "]时遇到异常", e);
        }
    }

    /**
     * 私钥解密
     *
     * @param data
     * @param privateKeyStr
     * @return
     */

    public static String privateDecrypt(String data, String privateKeyStr) {
        try {

            RSAPrivateKey privateKey = RSAUtil.getPrivateKey(privateKeyStr);
            Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, privateKey);
            return new String(rsaSplitCodec(cipher, Cipher.DECRYPT_MODE, Base64.decodeBase64(data), privateKey.getModulus().bitLength()), CHARSET);
        } catch (Exception e) {
            throw new RuntimeException("解密字符串[" + data + "]时遇到异常", e);
        }
    }


    private static byte[] rsaSplitCodec(Cipher cipher, int opmode, byte[] datas, int keySize) {
        int maxBlock = 0;
        if (opmode == Cipher.DECRYPT_MODE) {
            maxBlock = keySize / 8;
        } else {
            maxBlock = keySize / 8 - 11;
        }
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offSet = 0;
        byte[] buff;
        int i = 0;
        try {
            while (datas.length > offSet) {
                if (datas.length - offSet > maxBlock) {
                    buff = cipher.doFinal(datas, offSet, maxBlock);
                } else {
                    buff = cipher.doFinal(datas, offSet, datas.length - offSet);
                }
                out.write(buff, 0, buff.length);
                i++;
                offSet = i * maxBlock;
            }
        } catch (Exception e) {
            throw new RuntimeException("加解密阀值为[" + maxBlock + "]的数据时发生异常", e);
        }
        byte[] resultDatas = out.toByteArray();
        IOUtils.closeQuietly(out);
        return resultDatas;
    }


    public static void main(String[] args) throws Exception {
//        //前端生成的单词秘钥
//        String singleKey = "ushsushyshshshsh";
//        //登录 单次秘钥的密文
//        String encodedData = RSAUtil.publicEncrypt(singleKey, RSAUtil.getPublicKey(PUBLIC_KEY));
//        
        //由上面产生的数据
        String encodeData = "DG2PpofPwPs6x4rVHWtD24y-c-U4pzAGSYrhhEfsWl8Eqp4HKTliUWYJ3YCkiEbSlvl2Q2GJA2YK49DNp0g6_YbDXGb0CuiDFHidIyc9bhM7fHi1C0TP-uY7mpgiAydvtJJGNo08t0aaywoYHT030P7Ao0MzIciyTT8Nm2yTekY";
        //====以上是其前端完成======

//        String aa = RSAUtil.publicEncrypt("123445567777",RSAUtil.getPublicKey(PUBLIC_KEY));

        //使用私钥解密前端单词秘钥的密文，解密出单次秘钥
        String singleKey = RSAUtil.privateDecrypt("b8Mr7redVjqtNiY2xnjBJ8cPanYJzlFNOrPiVehXU2gwtlXHn5+babdEv0U+AuxEg5g+B9/D3RHa4P5utzAp1T+9qlBJJyovHdJuuwibta+nIfl+j1Qj3QlCvvByDaOhVVyt9hFiHshiElyDgDe2XXtHeyUa4HzlMmpTH7kFbw0=",PRIVATE_KEY);

        





//        //后端生成会话秘钥，存储数据库和redis（会员id，uuid）
//        String sessionSecret = createSessionSecret();
//        //用单次秘钥使用AES方式加密会员秘钥
//        String encryptSessionSecret = AESUtil.encrypt(sessionSecret,singleKey);
//        //下面是前端的验证
//        

    }



}
